<template>
  <md-main>
    <el-collapse-transition>
      <div class="md-body mb20" v-show="showSearch">
        <el-form :model="search" ref="search" size="small" :inline="true">
          <el-form-item label="部门名称" prop="deptName">
            <el-input v-model="search.deptName" class="w150" placeholder="请输入部门名称" clearable />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <md-dict-select :options="dictData['sys_normal_disable']" v-model="search.status" placeholder="请选择状态" class="w150"></md-dict-select>
          </el-form-item>
          <el-form-item>
            <md-button type="primary" icon="el-icon-search" @click="handleQuery()">搜索</md-button>
            <md-button icon="el-icon-refresh" @click="handleQueryReset()">重置</md-button>
          </el-form-item>
        </el-form>
      </div>
    </el-collapse-transition>

    <div class="md-body md-table">
      <md-toolbar>
        <md-button type="primary" size="small" plain :prems="['system:menu:add']" @click="handleAdd()">新增</md-button>

        <template slot="right">
          <md-button size="mini" icon="el-icon-search" circle @click="showSearch=!showSearch"></md-button>
          <md-button type="primary" size="mini" icon="el-icon-refresh" circle @click="getTableDataList()"></md-button>
        </template>
      </md-toolbar>

      <el-table v-loading="tableLoading" :data="tableData" row-key="deptId" default-expand-all :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
        <el-table-column prop="deptName" label="部门名称" :show-overflow-tooltip="true" width="200"></el-table-column>

        <el-table-column prop="orderNum" label="排序" min-width="60"></el-table-column>

        <el-table-column prop="status" label="状态" min-width="80">
          <template slot-scope="{ $index, row }">
            <md-dict-tag :options="dictData['sys_normal_disable']" :value="row.status"></md-dict-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="170" />
        <el-table-column label="操作" align="center" fixed="right" width="200">
          <template slot-scope="{ row }">
            <md-button size="mini" type="text" icon="el-icon-edit" :prems="['system:menu:edit']" @click="handleUpdate(row)">修改</md-button>
            <md-button size="mini" type="text" icon="el-icon-plus" :prems="['system:menu:add']" @click="handleAdd(row)">新增</md-button>
            <md-button size="mini" type="text" icon="el-icon-delete" :prems="['system:menu:remove']" @click="handleDelete(row)">删除</md-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="dialog.title" :visible.sync="dialog.open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="request" :rules="rules" size="small" label-width="100px" label-position="right">
        <el-form-item label="上级" prop="parentId">
          <md-select-tree ref="mdDeptSelectTree" v-model="request.parentId" :data="dialog.deptData" :defaultProps="{label: 'deptName', value: 'deptId'}" placeholder="请选择上级"></md-select-tree>
        </el-form-item>

        <el-form-item label="部门名称" prop="deptName">
          <el-input v-model="request.deptName" placeholder="请输入部门名称" />
        </el-form-item>

        <el-form-item label="部门顺序" prop="orderNum">
          <el-input-number v-model="request.orderNum" controls-position="right" :min="0" />
        </el-form-item>

        <el-form-item label="负责人" prop="leader">
          <el-input v-model="request.leader" placeholder="请输入负责人" />
        </el-form-item>

        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="request.phone" placeholder="请输入联系电话" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="request.email" placeholder="请输入邮箱" />
        </el-form-item>

        <el-form-item label="岗位状态" prop="status">
          <md-dict-radio-group :options="dictData['sys_normal_disable']" v-model="request.status"></md-dict-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="handleSubmit">确 定</el-button>
        <el-button size="small" @click="handleCancel">取 消</el-button>
      </div>
    </el-dialog>
  </md-main>
</template>

<script>
import { delDept, treeListDept, getDept } from '@/api/system/dept.service.js'
import { mdGetDictData } from '@/ddd/dict.service.js'
export default {
  name: 'MdSystemDeptComponent',
  data () {
    return {
      // 显示隐藏查询条件
      showSearch: true,
      // 查询参数
      search: searchParams,
      // 列表加载
      tableLoading: false,
      // 列表数据
      tableData: [],
      // 添加/编辑请求参数
      request: requestParams,
      rules: rules,
      // 添加/编辑弹窗
      dialog: {
        title: '添加部门',
        open: false,
        deptData: []
      },
      dictData: {}
    }
  },
  mounted () {
    mdGetDictData(['sys_normal_disable']).then(res => {
      this.dictData = res
    })

    this.getTableDataList()
  },
  methods: {
    /** 获取菜单数据 */
    async getTableDataList () {
      this.tableLoading = true

      try {
        const res = await treeListDept(this.search)

        this.tableData = []
        this.tableData = res.data
        this.dialog.deptData = []
        this.dialog.deptData = [{ deptId: 0, deptName: '一级部门', parentId: 0, children: res.data }]
      } catch (error) {
        console.log(error)
      }

      this.tableLoading = false
    },
    /** 搜索 */
    handleQuery () {
      this.search.pageNum = 1

      this.getTableDataList()
    },
    /** 重置搜索 */
    handleQueryReset () {
      this.search = { ...searchParams }

      this.getTableDataList()
    },
    // 重置表单数据
    handleReset () {
      this.request = { ...requestParams }
      if (this.$refs.form) {
        this.$refs.form.resetFields();
      }
    },
    /** 删除 */
    async handleDelete (row) {
      try {
        await this.$confirm(`是否确认删除名称为 ${row.menuName} 的数据项？`)

        await delDept(row.deptId)

        this.$message.success('删除成功')

        this.getTableDataList()
      } catch (error) {
        console.log(error)
      }
    },
    /** 添加 */
    async handleAdd (row) {
      try {
        this.handleReset()

        this.dialog.title = '添加部门'

        this.request = { ...requestParams }

        this.request.parentId = row ? row.deptId : 0

        this.dialog.open = true

      } catch (error) {
        console.log(error)
      }
    },
    /** 更新 */
    async handleUpdate (row) {
      try {
        this.handleReset()

        const res = await getDept(row.deptId)

        this.request = res.data

        this.dialog.open = true

        this.dialog.title = '修改部门'

      } catch (error) {
        console.log(error)
      }
    },
    /** 保存 */
    handleSubmit () {
      console.log(this.$refs.mdDeptSelectTree.getTreeProp().getCurrentKey())
      console.log(this.$refs.mdDeptSelectTree.getTreeProp().getCurrentNode())
      console.log(this.$refs.mdDeptSelectTree.getTreeProp().getNode())

      const keys = this.$refs.mdDeptSelectTree.getTreeProp().getCheckedKeys()
      const nodes = this.$refs.mdDeptSelectTree.getTreeProp().getCheckedNodes()
      const halfKeys = this.$refs.mdDeptSelectTree.getTreeProp().getHalfCheckedKeys()
      const halfNodes = this.$refs.mdDeptSelectTree.getTreeProp().getHalfCheckedNodes()

      console.log(keys, nodes, halfKeys, halfNodes)

      // this.$refs.form.validate(async valid => {
      //   if (!valid) {
      //     return
      //   }

      //   try {
      //     const params = Object.assign({}, { ...this.request })

      //     await (params.menuId === undefined ? insertDept : updateDept)(params)

      //     this.$message.success(params.menuId === undefined ? '添加成功' : '修改成功')

      //     this.dialog.open = false;

      //     this.getTableDataList()
      //   } catch (error) {
      //     console.log(error)
      //   }
      // })
    },
    handleCancel () {
      this.dialog.open = false

      this.handleReset()
    }
  }
}
const searchParams = {
  parentId: undefined,
  ancestors: undefined,
  deptName: undefined,
  leader: undefined,
  phone: undefined,
  email: undefined,
  status: undefined,
  createBy: undefined,
  updateBy: undefined,
  beginDate: undefined,
  endDate: undefined,
  orderBy: 'order_num',
  isDesc: false
}

const requestParams = {
  menuId: undefined,
  parentId: 0,
  ancestors: undefined,
  deptName: undefined,
  orderNum: 100,
  leader: undefined,
  phone: undefined,
  email: undefined,
  status: '0'
}

const rules = {
  deptName: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
  parentId: [{ required: true, message: '请选择上级', trigger: 'change' }]
}
</script>